<template>
  <!--  流程配置 start-->
  <a-drawer
    :visible="flowDrawerVisible"
    :width="900"
    unmountOnClose
    @ok="handelFlowTaskOk"
    @cancel="handelCloseFlowTaskDrawer"
    class="add-drawer"
  >
    <template #header>
      <CustomTitle :title="(taskEditType == 'add' ? '添加' : '编辑') + '任务'" />
    </template>
    <div class="drawer-content" v-if="isLoaded">
      <a-form :model="processForm" ref="processFormRef">
        <a-space>
          <a-form-item label="客户阶段" field="stageName">
            {{ stageDetail.stageName }}
          </a-form-item>
          <a-form-item label="任务名称" field="taskName" :rules="[...rules, { maxLength: 15, message: '长度不能超过15个字符' }]">
            <a-input v-model="processForm.taskName" />
          </a-form-item>
        </a-space>
        <a-space>
          <a-form-item
            label="排序号"
            field="orderNum"
            :rules="[...rules, { match: /^[1-9]\d{0,9}$/, message: '请输入大于0但小于10位的正整数' }]"
          >
            <a-input-number v-model="processForm.orderNum" />
          </a-form-item>
          <a-form-item label="前置条件" field="beforeFieldId">
            <div class="link" @click="showBeforeCondition">
              <icon-plus-circle-fill size="20" />
              设置（{{ preConditionList.length }}）
            </div>
          </a-form-item>
        </a-space>
        <a-space>
          <a-form-item label="责任人" field="roleId" :rules="{ required: true, message: '请选择' }">
            <a-select v-model="processForm.roleId">
              <a-option v-for="item in roleList" :key="item.roleId" :value="item.roleId">
                {{ item.roleName }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="关联表单" field="formId" :rules="{ required: true, message: '请选择' }">
            <SelectSearch
              :defaultSelectId="processForm.formId"
              :default-select-list="defaultSelectFormList"
              :requestApi="getSelectFormList"
              :config="searchFormConfig"
              @change-select="changeForm"
            />
          </a-form-item>
        </a-space>
        <a-space>
          <a-form-item label="间隔天数" field="intervalDays">
            <a-input-number v-model="processForm.intervalDays" :min="0" :max="1000000000" :precision="0" />
          </a-form-item>
          <a-form-item label="跟进周期" field="trackDays">
            <a-input-number v-model="processForm.trackDays" :min="0" :max="1000000000" :precision="0" />
          </a-form-item>
        </a-space>
        <a-space>
          <a-form-item
            label="标准天数"
            field="executeDays"
            :rules="[...rules, { match: /^([1-9]|[12][0-9]|30)$/, message: '请输入1-30的正整数' }]"
          >
            <a-input-number v-model="processForm.executeDays" />
          </a-form-item>
          <a-form-item label="任务执行" field="workDateType">
            <a-radio-group v-model="processForm.workDateType">
              <a-radio :value="1">所有日期</a-radio>
              <a-radio :value="2">只在工作日</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-space>
        <a-space>
          <a-form-item label="是否外出" field="isOut" :rules="{ required: true, message: '请选择' }">
            <a-radio-group v-model="processForm.isOut">
              <a-radio :value="1">是</a-radio>
              <a-radio :value="0">否</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="是否启用" field="status">
            <a-switch v-model="processForm.status" :unchecked-value="0" :checked-value="1" />
          </a-form-item>
        </a-space>
        <a-space>
          <a-form-item label="是否验收" field="checkType">
            <div class="is-acceptance" :style="{ height: processForm.checkType.length ? 'auto' : '40px' }">
              <a-checkbox-group v-model="(processForm.checkType as any)">
                <a-checkbox :value="1">内部</a-checkbox>
                <a-checkbox :value="2">客户</a-checkbox>
              </a-checkbox-group>
              <div class="select" v-if="processForm.checkType.length">
                <a-cascader
                  :options="templateTree"
                  @change="changeAcceptance as any"
                  v-model="processForm.standardId"
                  :field-names="fieldNames"
                  placeholder="请选择"
                />
              </div>
            </div>
          </a-form-item>
          <div class="form-item__is-audit">
            <a-form-item label="审批通过才进行下一步" field="isAudit">
              <a-switch v-model="processForm.isAudit" :unchecked-value="false" :checked-value="true" />
            </a-form-item>
          </div>
        </a-space>
        <a-space>
          <a-form-item
            v-if="preConditionList.length > 0"
            label="指派时间"
            field="assignTimeType"
            :class="[processForm.checkType.length > 0 ? 'top-distance' : '']"
          >
            <a-checkbox v-model="processForm.assignTimeType">该任务可设置后置任务计划开始时间</a-checkbox>
          </a-form-item>
          <a-form-item></a-form-item>
        </a-space>
      </a-form>
      <div class="desc">操作说明</div>
      <QuillEditor v-model:content="processForm.remark" :toolbar="toolbar" contentType="html" ref="myQuillEditor" />
      <input
        type="file"
        name="file"
        @change="changeImage"
        ref="uploadFileImage"
        style="opacity: 0; width: 0; height: 0; cursor: pointer"
      />
    </div>
  </a-drawer>
  <!-- 流程配置 end -->

  <!--  start 前置条件-->
  <a-modal v-model:visible="conditionVisible" hide-title>
    <CustomTitle title="设置前置条件" />
    <div class="condition-list">
      <div class="condition-item" v-for="(item, index) in preConditionList" :key="item">
        <a-row>
          <a-col :span="22">
            <div class="content">
              <div class="condition-label">前置流程</div>
              <a-select
                @change="changeBeforeTaskSetting($event, item) as any"
                @clear="handelClearBeforeTask(item)"
                allow-clear
                v-model="item.beforeTaskSettingId"
                placeholder="请选择"
              >
                <a-option
                  v-for="processItem in beforeTaskList"
                  :value="processItem.taskSettingId"
                  :key="processItem.taskSettingId"
                  >{{ processItem.taskName }}
                </a-option>
              </a-select>
            </div>
            <div class="content">
              <div class="condition-label">前置条件</div>
              <a-select
                v-model="item.beforeFieldId"
                placeholder="请选择"
                @change="changeBeforeField($event, item) as any"
                @clear="handelClearBeforeField(item)"
                allow-clear
              >
                <a-option v-for="beforeItem in item.beforeFields" :value="beforeItem.id" :key="beforeItem.id"
                  >{{ beforeItem.title }}
                </a-option>
              </a-select>
              <a-select style="margin-left: 10px" v-model="item.beforeFieldVal" placeholder="请选择" allow-clear>
                <a-option v-for="fieldItem in item.beforeFieldOptions" :value="fieldItem" :key="fieldItem"
                  >{{ fieldItem }}
                </a-option>
              </a-select>
            </div>
          </a-col>
          <a-col :span="2">
            <div class="delete" @click="delBeforeCondition(index)">
              <icon-delete size="18" />
            </div>
          </a-col>
        </a-row>
      </div>
      <div class="add-item" @click="addBeforeCondition">
        <icon-plus-circle-fill size="20" />
        <span>添加</span>
      </div>
    </div>
    <template #footer>
      <div class="btn-footer">
        <a-button @click="conditionVisible = false">取消</a-button>
        <a-button type="primary" @click="beforeConditionConfirm">确定</a-button>
      </div>
    </template>
  </a-modal>
  <!--  end 前置条件-->
</template>
<script setup lang="ts">
import type { beforeConditionItem, ProcessTaskItem } from "@/apis/system/type";
import { Message } from "@arco-design/web-vue";
import {
  addBusTaskTemplate,
  getSelectFormList,
  formFieldByFormId,
  preProcess,
  processDetail,
  editBusTaskTemplate
} from "@/apis/system";
import { cloneDeep } from "lodash";
import { getRoleList } from "@/apis/role";
import { standardTemplateTree } from "@/apis/projectConfig";
import multipartOssStore from "@/stores/modules/multipartOssStore";
import { getCurrentInstance, onMounted } from "vue";

const props = defineProps([
  "taskEditType",
  "rules",
  "stageDetail",
  "currentPortraitId",
  "currentTaskSettingId",
  "currentStageType"
]);
const { proxy }: any = getCurrentInstance();
const $emit = defineEmits(["handleTask"]);

const processForm = ref<ProcessTaskItem>({
  taskName: "",
  isMust: 1,
  formName: "",
  roleId: "",
  executeDays: 1,
  intervalDays: 0,
  trackDays: 0,
  formId: "",
  status: 1,
  isOut: 0,
  orderNum: 1,
  remark: "",
  workDateType: 1,
  checkType: [],
  standardId: "",
  modelId: "",
  isCheck: 0,
  taskType: 1, //普通任务 2整改任务 3任务模版
  isAudit: false,
  assignTimeType: false
});
const flowDrawerVisible = ref(true);
const processVerify = (): Promise<boolean> => {
  return new Promise(async resolve => {
    proxy.$refs.processFormRef.validate((error: any) => {
      resolve(error == void 0);
    });
  });
};
const handelFlowTaskOk = async () => {
  if (!(await processVerify())) {
    return Message.error("请填写完整信息");
  }
  const postData = cloneDeep(processForm.value);
  postData.intervalDays = postData.intervalDays ?? 0;
  postData.trackDays = postData.trackDays ?? 0;
  let checkTypeLable: string[] = [];
  (postData.checkType as []).forEach((v: any) => {
    checkTypeLable.push(v === 1 ? "内部" : "客户");
  });
  postData.isCheck = checkTypeLable?.length ? 1 : 0;
  postData.taskTriggerConditionSettings = preConditionList.value;
  if (props.taskEditType === "add") {
    await addBusTaskTemplate({
      ...postData,
      portraitId: props.currentPortraitId,
      stageSettingId: props.stageDetail?.stageSettingId,
      checkType: checkTypeLable.join(",")
    });
  }
  if (props.taskEditType === "edit") {
    await editBusTaskTemplate(props.currentTaskSettingId, {
      ...postData,
      portraitId: props.currentPortraitId,
      stageSettingId: props.stageDetail?.stageSettingId,
      checkType: checkTypeLable.join(",")
    });
  }

  Message.success("操作成功");
  handelCloseFlowTaskDrawer();
  // init();
};
const handelCloseFlowTaskDrawer = async () => {
  await nextTick();
  proxy.$refs.processFormRef.resetFields();
  processForm.value = {
    taskName: "",
    isMust: 1,
    roleId: "",
    executeDays: 1,
    intervalDays: 0,
    trackDays: 0,
    formId: "",
    status: 1,
    isOut: 0,
    orderNum: 1,
    remark: "",
    workDateType: 1,
    checkType: [],
    standardId: "",
    modelId: "",
    isCheck: 0,
    taskType: 1, //普通任务 2整改任务 3任务模版
    isAudit: false
  };
  defaultSelectFormList.value = [];
  preConditionList.value = [];
  flowDrawerVisible.value = false;
  $emit("handleTask");
};

//获取责任人列表
const roleList = ref([]) as any;
const getLeaderList = async () => {
  const res = await getRoleList();
  roleList.value = res.data ?? [];
};

//关联表单
const searchFormConfig = {
  label: "formName",
  value: "formId",
  keyword: "formName"
};
const defaultSelectFormList = ref([]) as any;
const changeForm = (data: any) => {
  processForm.value.formId = data.formId;
  processForm.value.formName = data.formName;
};

/**
 * 是否验收级联选择器
 * TODO：网上复制的，虽然不怎么样，将就用
 */
const fieldNames = { value: "standardId", label: "standardName" };
const templateTree = ref<any[]>([]);
const getTree = (tree: any[]): any[] => {
  tree.forEach(v => {
    if (v.children && Array.isArray(v.children)) {
      for (let i = 0; i < v.children.length; i++) {
        const child = v.children[i];
        delete child.children;
      }
    }
  });
  return tree;
};
const getTemplateTree = async () => {
  const { data } = await standardTemplateTree();
  templateTree.value = getTree(data);
};
const changeAcceptance = (value: string) => {
  const ids = getParentNodes(value, templateTree.value);
  if (ids?.length) {
    return (processForm.value.modelId = ids[0].standardId);
  }
  processForm.value.modelId = "";
  processForm.value.standardId = "";
};
const getParentNodes = (id: string, tree: any[]) => {
  getParentNodesByChildrenId([], id, tree);
  return nodes;
};
let nodes: any[] = [];
const getParentNodesByChildrenId = (his: any[], targetId: string, tree: any[]) => {
  tree.some(list => {
    const children = list.children || [];
    if (list.standardId === targetId) {
      nodes = his;
      return true;
    } else if (children.length > 0) {
      const history = [...his];
      history.push(list);
      return getParentNodesByChildrenId(history, targetId, children);
    }
  });
};

//前置条件
const beforeTaskList = ref<ProcessTaskItem[]>([]);
const preConditionList = ref<beforeConditionItem[]>([]);
const conditionVisible = ref(false);
const showBeforeCondition = () => {
  conditionVisible.value = true;
};
const beforeConditionConfirm = () => {
  if (preConditionList.value.length > 0) {
    const hasDuplicateSampleTypeId = preConditionList.value.some((item, index, array) => {
      return array.filter(innerItem => innerItem.beforeTaskSettingId === item.beforeTaskSettingId).length > 1;
    });
    if (hasDuplicateSampleTypeId) {
      return Message.error("前置条件不能重复");
    }
    conditionVisible.value = false;
  }
};
const getPreProcessList = async () => {
  const { data } = await preProcess(props.currentPortraitId, props.currentStageType);
  beforeTaskList.value = data ?? [];
};
// 前置任务对应表单字段列表
const getFormField = async (formId: string, params?: { fieldName: string }, item: any) => {
  const { data } = await formFieldByFormId(formId, params);
  item.beforeFields = data ?? [];
  item.beforeFieldOptions = [];
};
const changeBeforeTaskSetting = (e: string, item: { beforeFieldId: string; beforeFieldVal: string }) => {
  if (!e) return;
  const taskObj: any = beforeTaskList.value.find(v => v.taskSettingId === e);
  item.beforeFieldId = "";
  item.beforeFieldVal = "";
  getFormField(taskObj.formId, { fieldName: "SelectInput" }, item);
};
const handelClearBeforeTask = (item: any) => {
  item.beforeFields = [];
  item.beforeFieldOptions = [];
  item.beforeFieldId = "";
  item.beforeFieldVal = "";
  item.beforeFieldName = "";
};
const changeBeforeField = (e: string, item: { beforeFieldName: string; beforeFieldVal: string }) => {
  if (!e) return;
  const fieldObj: any = item.beforeFields.find(v => v.id === e);
  item.beforeFieldName = fieldObj?.title || "";
  item.beforeFieldOptions = fieldObj?.props?.options || [];
  item.beforeFieldVal = "";
};
const handelClearBeforeField = (item: { beforeFieldVal: string; beforeFieldName: string }) => {
  item.beforeFieldOptions = [];
  item.beforeFieldVal = "";
  item.beforeFieldName = "";
};
const addBeforeCondition = () => {
  preConditionList.value.push({});
};
const delBeforeCondition = (index: number) => {
  preConditionList.value.splice(index, 1);
};

//操作说明
const multipartOss = multipartOssStore();
const uploadFileImage = ref(null);
const toolbar = {
  container: [
    [{ header: [1, 2, 3, 4, 5, 6, false] }],
    ["bold", "italic", "underline", "strike"],
    ["blockquote", "code-block"],
    ["image"],
    [{ list: "ordered" }, { list: "bullet" }, { list: "check" }],
    [{ script: "sub" }, { script: "super" }],
    [{ color: [] }, { background: [] }],
    [{ align: [] }]
  ],
  handlers: {
    image: function () {
      // 劫持原来的图片点击按钮事件
      (uploadFileImage as any).value.value = "";
      (uploadFileImage as any).value.click();
    }
  }
};
const myQuillEditor = ref(null);
const insertEle = (url: string) => {
  let quill = (myQuillEditor as any).value.getQuill();
  let length = quill.getSelection().index;
  quill.insertEmbed(length, "image", url);
  // // 调整光标到最后
  quill.setSelection(length + 1);
};
const changeImage = (value: any) => {
  const file = value.target.files[0];
  const objName = `crm/${file.name}`;
  multipartOss.submit(objName, file).then(async () => {
    await multipartOss.setACL(objName, "public-read");
    const fileUrl = await multipartOss.signatureUrl(objName);
    insertEle(fileUrl);
  });
};

//获取详情
const isLoaded = ref(false);
const getDetail = async () => {
  const { data } = await processDetail(props.currentTaskSettingId);
  processForm.value = data;
  preConditionList.value = data.taskTriggerConditionSettings;
  if (preConditionList.value.length > 0) {
    preConditionList.value.map(item => {
      editFilterOptions(item.beforeTaskFormId, { fieldName: "SelectInput" }, item);
    });
  }
  let checkTypes: number[] = [];
  (processForm.value.checkType as string)?.split(",")?.forEach((item: any) => {
    checkTypes.push(item === "内部" ? 1 : 2);
  });
  processForm.value.checkType = checkTypes;

  defaultSelectFormList.value = [
    {
      formId: processForm.value.formId,
      formName: processForm.value.formName
    }
  ];
  isLoaded.value = true;
};
// 前置任务对应表单字段列表
const editFilterOptions = async (formId: string, params?: { fieldName: string }, item: any) => {
  const { data } = await formFieldByFormId(formId, params);
  item.beforeFields = data ?? [];
  const fieldObj: any = item.beforeFields.find(v => v.id === item.beforeFieldId);
  item.beforeFieldName = fieldObj?.title || "";
  item.beforeFieldOptions = fieldObj?.props?.options || [];
};
onMounted(() => {
  getLeaderList();
  getTemplateTree();
  getPreProcessList();
  if (props.taskEditType == "edit") {
    getDetail();
  } else {
    isLoaded.value = true;
  }
});
</script>

<style scoped lang="scss">
@import "../index.scss";

.top-distance {
  margin-top: 30px;
}

.form-item__is-audit {
  width: 100%;

  :deep(.arco-row) {
    flex-flow: row nowrap;
  }

  :deep(.arco-form-item-label-col) {
    width: 180px;
    padding-left: 16px;
  }

  :deep(.arco-form-item-label) {
    width: 160px;
  }
}
</style>
<style lang="scss">
.add-drawer {
  .arco-drawer-header {
    padding: 20px 20px 0;
    border: none;
  }
}
</style>
